// result.js
Page({
  data: {
    results: [],
    originalImage: '',
    correctCount: 0,
    errorCount: 0,
    uncertainCount: 0,
    highlightedIndex: -1,
    canvasStyleWidth: 0,
    canvasStyleHeight: 0
  },

  onLoad(options) {
    console.log('结果页面加载，options:', options)
    
    // 接收从首页传递的数据
    const eventChannel = this.getOpenerEventChannel()
    if (eventChannel) {
      console.log('eventChannel存在，设置数据监听器')
      eventChannel.on('acceptDataFromOpenerPage', (data) => {
        console.log('接收到数据:', data)
        this.setData({
          results: data.results || [],
          originalImage: data.originalImage || ''
        })
        this.calculateSummary()
        
        // 数据设置完成后，延迟绘制
        setTimeout(() => {
          console.log('数据设置完成，开始绘制')
          this.drawOverlay()
        }, 300)
      })
    } else {
      console.log('eventChannel不存在，尝试其他方式获取数据')
    }
  },

  onReady() {
    // 页面渲染完成后绘制标注
    console.log('页面渲染完成，开始绘制标注')
    setTimeout(() => {
      this.drawOverlay()
    }, 500)
  },

  // 图片加载完成后设置Canvas样式尺寸
  onImageLoad() {
    const query = wx.createSelectorQuery().in(this)
    query.select('.original-image').boundingClientRect((rect) => {
      if (rect) {
        const w = rect.width || 400
        const h = rect.height || 300
        console.log('onImageLoad 获取图片尺寸:', rect)
        this.setData({ canvasStyleWidth: w, canvasStyleHeight: h })
        // 额外日志：容器和Canvas位置
        wx.createSelectorQuery().in(this).select('.image-container').boundingClientRect(r1 => {
          console.log('容器尺寸与位置:', r1)
        }).select('#overlayCanvas').boundingClientRect(r2 => {
          console.log('Canvas CSS实时尺寸与位置:', r2)
        }).exec()
      }
    }).exec()
  },

  // 监听数据变化
  onDataChange() {
    const results = this.data.results
    console.log('数据变化监听器触发，结果数量:', results.length)
    
    if (results && results.length > 0) {
      console.log('数据变化后开始绘制')
      this.drawOverlay()
    }
  },

  // 手动触发数据检查
  checkAndDraw() {
    console.log('手动检查数据并绘制')
    const results = this.data.results
    console.log('当前结果数据:', results)
    
    if (results && results.length > 0) {
      console.log('手动检查到数据，开始绘制')
      this.drawOverlay()
    } else {
      console.log('手动检查无数据')
    }
  },

  // 计算统计信息
  calculateSummary() {
    const results = this.data.results
    let correctCount = 0
    let errorCount = 0
    let uncertainCount = 0

    // 处理置信度显示
    results.forEach(item => {
      item.confidencePercent = Math.round(item.confidence * 100)
      
      if (item.isCorrect) {
        correctCount++
      } else if (item.confidence < 0.8) {
        uncertainCount++
      } else {
        errorCount++
      }
    })

    this.setData({
      results,
      correctCount,
      errorCount,
      uncertainCount
    })
  },

  // 在图片上绘制错误标记和正确答案
  async drawOverlay() {
    try {
      const results = this.data.results
      console.log('开始绘制标注，结果数量:', results.length)
      
      if (results.length === 0) {
        console.log('没有结果数据，跳过绘制')
        return
      }
      
      // 先尝试Canvas 2D
      const query = wx.createSelectorQuery().in(this)
      query.select('#overlayCanvas').fields({ node: true, size: true }).exec(async (res) => {
        console.log('Canvas查询结果:', res)
        
        if (res[0] && res[0].node) {
          console.log('Canvas 2D节点获取成功')
          const canvas = res[0].node
          const ctx = canvas.getContext('2d')
          
          if (!ctx) {
            console.log('Canvas 2D上下文获取失败，回退到旧版本')
            this.drawOverlayLegacy()
            return
          }
          
          console.log('Canvas 2D上下文获取成功')
          
                     // 获取图片尺寸信息
           query.select('.original-image').boundingClientRect((rect) => {
             if (rect) {
               console.log('图片尺寸信息:', rect)
               
               // 设置canvas尺寸为图片尺寸
               const windowInfo = wx.getWindowInfo()
               const dpr = windowInfo.pixelRatio || 1
               console.log('设备像素比:', dpr)
               
               // 使用图片的实际显示尺寸，如果为0则使用默认值
               const imageWidth = rect.width || 400
               const imageHeight = rect.height || 300
               
               // 设置Canvas的实际绘制尺寸
               canvas.width = imageWidth * dpr
               canvas.height = imageHeight * dpr
               ctx.scale(dpr, dpr)
               
               console.log('Canvas尺寸设置完成:', canvas.width, canvas.height)
               
                               // 设置Canvas的CSS尺寸，确保与图片显示尺寸一致
                const canvasElement = canvas
                if (canvasElement.style) {
                  canvasElement.style.width = imageWidth + 'px'
                  canvasElement.style.height = imageHeight + 'px'
                }
                
                // 强制更新Canvas的CSS样式
                setTimeout(() => {
                  this.updateCanvasStyle(canvas, imageWidth, imageHeight)
                }, 100)
               
               // 传递修正后的尺寸信息
               const correctedRect = {
                 ...rect,
                 width: imageWidth,
                 height: imageHeight
               }
               
               this.drawAnnotations(ctx, results, correctedRect)
             } else {
               console.log('未获取到图片尺寸信息，回退到旧版本')
               this.drawOverlayLegacy()
             }
           }).exec()
        } else {
          console.log('Canvas 2D节点获取失败，回退到旧版本')
          this.drawOverlayLegacy()
        }
      })
    } catch (error) {
      console.error('Canvas 2D初始化失败，回退到旧版本:', error)
      // 回退到旧版本
      this.drawOverlayLegacy()
    }
  },

  // 旧版本Canvas绘制方法（作为回退）
  drawOverlayLegacy() {
    console.log('使用旧版本Canvas绘制')
    const ctx = wx.createCanvasContext('overlayCanvas')
    const results = this.data.results

    console.log('旧版本Canvas上下文创建成功')

    // 获取图片尺寸信息
    const query = wx.createSelectorQuery().in(this)
    query.select('.original-image').boundingClientRect((rect) => {
      if (rect) {
        console.log('旧版本Canvas获取到图片尺寸:', rect)
        
        // 修正尺寸信息
        const correctedRect = {
          ...rect,
          width: rect.width || 400,
          height: rect.height || 300
        }
        
        this.drawAnnotationsLegacy(ctx, results, correctedRect)
      } else {
        console.log('旧版本Canvas未获取到图片尺寸')
      }
    }).exec()
  },

  // 绘制标注 - Canvas 2D版本
  drawAnnotations(ctx, results, imageRect) {
    console.log('开始绘制标注，图片尺寸:', imageRect)
    
    // 获取图片的实际显示尺寸
    const imageWidth = imageRect.width || 400
    const imageHeight = imageRect.height || 300
    
    console.log('Canvas实际尺寸:', ctx.canvas.width, ctx.canvas.height)
    console.log('绘制区域尺寸:', imageWidth, imageHeight)
    
    // 清除之前的绘制
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
    
    results.forEach((item, index) => {
      if (!item.isCorrect) {
        const pos = item.position
        console.log(`绘制项目 ${index}:`, pos)
        
        // 如果位置信息不完整，使用默认位置
        if (!pos || pos.width === 0 || pos.height === 0) {
          console.log(`位置信息不完整，跳过绘制:`, pos)
          return
        }
        
        const color = item.confidence < 0.8 ? '#ff8800' : '#ff4444'
        const lineWidth = item.confidence < 0.8 ? 3 : 4

        // 计算实际绘制位置（考虑图片缩放和位置偏移）
        const drawX = pos.x
        const drawY = pos.y
        const drawWidth = pos.width
        const drawHeight = pos.height

        console.log(`绘制位置: x=${drawX}, y=${drawY}, w=${drawWidth}, h=${drawHeight}`)

        // 绘制半透明背景 - 使用rgba格式
        const rgbaColor = color === '#ff4444' ? 'rgba(255, 68, 68, 0.2)' : 'rgba(255, 136, 0, 0.2)'
        ctx.fillStyle = rgbaColor
        ctx.fillRect(drawX - 2, drawY - 2, drawWidth + 4, drawHeight + 4)

        // 绘制错误标记框
        ctx.strokeStyle = color
        ctx.lineWidth = lineWidth
        ctx.setLineDash([5, 5])
        ctx.strokeRect(drawX, drawY, drawWidth, drawHeight)

        // 绘制错误标记（X形）
        ctx.setLineDash([])
        ctx.lineWidth = lineWidth + 1
        ctx.beginPath()
        ctx.moveTo(drawX, drawY)
        ctx.lineTo(drawX + drawWidth, drawY + drawHeight)
        ctx.moveTo(drawX + drawWidth, drawY)
        ctx.lineTo(drawX, drawY + drawHeight)
        ctx.stroke()

        // 添加错误类型标签背景
        const labelWidth = 80
        const labelHeight = 25
        ctx.fillStyle = color
        ctx.fillRect(drawX + drawWidth + 5, drawY + drawHeight / 2 - 12, labelWidth, labelHeight)

        // 添加错误类型标签文字
        ctx.fillStyle = '#ffffff'
        ctx.font = '12px sans-serif'
        const errorType = item.confidence < 0.8 ? '疑是错误' : '错误'
        ctx.fillText(errorType, drawX + drawWidth + 10, drawY + drawHeight / 2 + 3)

        // 添加正确答案提示背景
        if (item.correctAnswer !== null) {
          let correctText = ''
          
          switch (item.type) {
            case 'division_with_remainder':
              correctText = `正确答案: ${item.correctAnswer.quotient}...${item.correctAnswer.remainder}`
              break
            case 'fraction':
              correctText = `正确答案: ${item.correctAnswer.numerator}/${item.correctAnswer.denominator}`
              break
            default:
              correctText = `正确答案: ${item.correctAnswer}`
          }
          
          const textMetrics = ctx.measureText(correctText)
          const textWidth = textMetrics.width + 20
          const textHeight = 20
          
          ctx.fillStyle = '#00aa00'
          ctx.fillRect(drawX + drawWidth + 5, drawY + drawHeight / 2 + 8, textWidth, textHeight)
          
          // 添加正确答案文字
          ctx.fillStyle = '#ffffff'
          ctx.font = '11px sans-serif'
          ctx.fillText(correctText, drawX + drawWidth + 10, drawY + drawHeight / 2 + 20)
        }
      }
    })
    
    console.log('Canvas 2D绘制完成')
  },

  // 绘制标注 - 旧版本Canvas（作为回退）
  drawAnnotationsLegacy(ctx, results, imageRect) {
    console.log('开始旧版本Canvas绘制，图片尺寸:', imageRect)
    console.log('结果数据:', results)
    
    let drawCount = 0
    
    results.forEach((item, index) => {
      if (!item.isCorrect) {
        const pos = item.position
        console.log('绘制项目:', index, '位置:', pos, '类型:', item.type)
        
        if (!pos || !pos.x || !pos.y || !pos.width || !pos.height) {
          console.log('位置信息不完整，跳过绘制')
          return
        }
        
        const color = item.confidence < 0.8 ? '#ff8800' : '#ff4444'
        const lineWidth = item.confidence < 0.8 ? 3 : 4

        // 计算实际绘制位置（考虑图片缩放）
        const scaleX = imageRect.width / (pos.width || 1)
        const scaleY = imageRect.height / (pos.height || 1)
        
        const drawX = pos.x * scaleX
        const drawY = pos.y * scaleY
        const drawWidth = pos.width * scaleX
        const drawHeight = pos.height * scaleY

        console.log('计算后的绘制位置:', { drawX, drawY, drawWidth, drawHeight })

        // 绘制半透明背景 - 使用rgba格式
        const rgbaColor = color === '#ff4444' ? 'rgba(255, 68, 68, 0.2)' : 'rgba(255, 136, 0, 0.2)'
        ctx.setFillStyle(rgbaColor)
        ctx.fillRect(drawX - 2, drawY - 2, drawWidth + 4, drawHeight + 4)

        // 绘制错误标记框
        ctx.setStrokeStyle(color)
        ctx.setLineWidth(lineWidth)
        ctx.setLineDash([5, 5])
        ctx.strokeRect(drawX, drawY, drawWidth, drawHeight)

        // 绘制错误标记（X形）
        ctx.setLineDash([])
        ctx.setLineWidth(lineWidth + 1)
        ctx.beginPath()
        ctx.moveTo(drawX, drawY)
        ctx.lineTo(drawX + drawWidth, drawY + drawHeight)
        ctx.moveTo(drawX + drawWidth, drawY)
        ctx.lineTo(drawX, drawY + drawHeight)
        ctx.stroke()

        // 添加错误类型标签背景
        const labelWidth = 80
        const labelHeight = 25
        ctx.setFillStyle(color)
        ctx.fillRect(drawX + drawWidth + 5, drawY + drawHeight / 2 - 12, labelWidth, labelHeight)

        // 添加错误类型标签文字
        ctx.setFillStyle('#ffffff')
        ctx.setFontSize(12)
        const errorType = item.confidence < 0.8 ? '疑是错误' : '错误'
        ctx.fillText(errorType, drawX + drawWidth + 10, drawY + drawHeight / 2 + 3)

        // 添加正确答案提示背景
        if (item.correctAnswer !== null) {
          let correctText = ''
          
          switch (item.type) {
            case 'division_with_remainder':
              correctText = `正确答案: ${item.correctAnswer.quotient}...${item.correctAnswer.remainder}`
              break
            case 'fraction':
              correctText = `正确答案: ${item.correctAnswer.numerator}/${item.correctAnswer.denominator}`
              break
            default:
              correctText = `正确答案: ${item.correctAnswer}`
          }
          
          const textWidth = ctx.measureText(correctText).width + 20
          const textHeight = 20
          
          ctx.setFillStyle('#00aa00')
          ctx.fillRect(drawX + drawWidth + 5, drawY + drawHeight / 2 + 8, textWidth, textHeight)
          
          // 添加正确答案文字
          ctx.setFillStyle('#ffffff')
          ctx.setFontSize(11)
          ctx.fillText(correctText, drawX + drawWidth + 10, drawY + drawHeight / 2 + 20)
        }
        
        drawCount++
      }
    })
    
    console.log('旧版本Canvas绘制完成，共绘制了', drawCount, '个标注')
    ctx.draw()
  },

  // 点击图片时高亮对应的题目
  onImageTap(e) {
    const rect = e.currentTarget.getBoundingClientRect()
    const x = e.detail.x
    const y = e.detail.y
    
    // 查找点击位置对应的题目
    const results = this.data.results
    let clickedIndex = -1
    
    results.forEach((item, index) => {
      if (item.position) {
        const pos = item.position
        if (x >= pos.x && x <= pos.x + pos.width && 
            y >= pos.y && y <= pos.y + pos.height) {
          clickedIndex = index
        }
      }
    })
    
    if (clickedIndex !== -1) {
      this.highlightItem({ currentTarget: { dataset: { index: clickedIndex } } })
    }
  },

  // 高亮显示选中的题目
  highlightItem(e) {
    const index = e.currentTarget.dataset.index
    const results = this.data.results
    
    // 清除之前的高亮
    results.forEach((item, i) => {
      item.highlighted = i === index
    })

    this.setData({
      results,
      highlightedIndex: index
    })

    // 滚动到对应位置
    this.scrollToItem(index)
  },

  // 滚动到指定题目
  scrollToItem(index) {
    wx.createSelectorQuery()
      .select(`.result-item:nth-child(${index + 1})`)
      .boundingClientRect((rect) => {
        if (rect) {
          wx.pageScrollTo({
            scrollTop: rect.top - 100,
            duration: 300
          })
        }
      })
      .exec()
  },

  // 返回首页
  goBack() {
    wx.navigateBack({
      delta: 1
    })
  },

  // 保存结果
  saveResult() {
    const results = this.data.results
    const summary = {
      correctCount: this.data.correctCount,
      errorCount: this.data.errorCount,
      uncertainCount: this.data.uncertainCount,
      totalCount: results.length,
      timestamp: new Date().toISOString()
    }

    // 保存到本地存储
    const savedResults = wx.getStorageSync('correctionHistory') || []
    savedResults.unshift({
      id: Date.now(),
      summary,
      results,
      originalImage: this.data.originalImage
    })

    // 只保留最近10次记录
    if (savedResults.length > 10) {
      savedResults.splice(10)
    }

    wx.setStorageSync('correctionHistory', savedResults)

    wx.showToast({
      title: '结果已保存',
      icon: 'success'
    })
  },

  // 分享结果
  shareResult() {
    const summary = this.data
    const shareText = `口算批改结果：正确${summary.correctCount}题，错误${summary.errorCount}题，疑是错误${summary.uncertainCount}题`
    
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })

    // 复制到剪贴板
    wx.setClipboardData({
      data: shareText,
      success: () => {
        wx.showToast({
          title: '结果已复制',
          icon: 'success'
        })
      }
    })
  },

  // 分享给朋友
  onShareAppMessage() {
    const summary = this.data
    return {
      title: `口算批改结果：正确${summary.correctCount}题，错误${summary.errorCount}题`,
      path: '/pages/index/index',
      imageUrl: this.data.originalImage
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    const summary = this.data
    return {
      title: `口算批改结果：正确${summary.correctCount}题，错误${summary.errorCount}题`,
      imageUrl: this.data.originalImage
    }
  },

  // 预览原图
  previewOriginalImage() {
    wx.previewImage({
      urls: [this.data.originalImage]
    })
  },

  // 强制重绘Canvas
  forceRedraw() {
    console.log('强制重绘Canvas')
    this.drawOverlay()
  },

  // 强制使用旧版本Canvas
  forceLegacyCanvas() {
    console.log('强制使用旧版本Canvas')
    this.drawOverlayLegacy()
  },

  // 检查Canvas状态
  checkCanvasStatus() {
    console.log('=== 检查Canvas状态 ===')
    
    // 检查Canvas DOM元素
    const query = wx.createSelectorQuery().in(this)
    query.select('#overlayCanvas').fields({ node: true, size: true, rect: true }).exec((res) => {
      console.log('Canvas查询结果:', res)
      
      if (res[0] && res[0].node) {
        console.log('Canvas 2D节点存在')
        const canvas = res[0].node
        console.log('Canvas节点:', canvas)
        console.log('Canvas尺寸:', canvas.width, canvas.height)
        
        const ctx = canvas.getContext('2d')
        if (ctx) {
          console.log('Canvas 2D上下文可用')
        } else {
          console.log('Canvas 2D上下文不可用')
        }
      } else {
        console.log('Canvas 2D节点不存在')
      }
      
      // 检查Canvas的CSS样式
      query.select('#overlayCanvas').boundingClientRect((rect) => {
        if (rect) {
          console.log('Canvas CSS尺寸:', rect)
          console.log('Canvas位置:', rect.left, rect.top)
          console.log('Canvas可见性:', rect.width > 0 && rect.height > 0 ? '可见' : '不可见')
        } else {
          console.log('Canvas CSS尺寸获取失败')
        }
      }).exec()
      
      // 检查旧版本Canvas
      try {
        const legacyCtx = wx.createCanvasContext('overlayCanvas')
        console.log('旧版本Canvas上下文创建成功')
      } catch (error) {
        console.log('旧版本Canvas上下文创建失败:', error)
      }
    })
  },

  // 测试简单绘制
  testSimpleDraw() {
    console.log('测试简单绘制')
    
    const query = wx.createSelectorQuery()
    query.select('#overlayCanvas').fields({ node: true, size: true }).exec((res) => {
      if (res[0] && res[0].node) {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        
        console.log('Canvas测试绘制，尺寸:', canvas.width, canvas.height)
        
        // 清除画布
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        
        // 绘制测试图形 - 使用更明显的颜色和尺寸
        ctx.fillStyle = 'rgba(255, 0, 0, 0.8)'
        ctx.fillRect(0, 0, 200, 200)
        
        ctx.fillStyle = 'rgba(0, 0, 255, 0.8)'
        ctx.fillRect(200, 0, 200, 200)
        
        ctx.fillStyle = 'rgba(0, 255, 0, 0.8)'
        ctx.fillRect(0, 200, 200, 200)
        
        ctx.fillStyle = 'rgba(255, 255, 0, 0.8)'
        ctx.fillRect(200, 200, 200, 200)
        
        // 添加文字
        ctx.fillStyle = 'white'
        ctx.font = '24px Arial'
        ctx.fillText('测试绘制', 50, 100)
        ctx.fillText('Canvas工作正常', 50, 300)
        
        console.log('简单绘制测试完成')
      } else {
        console.log('Canvas 2D不可用，尝试旧版本')
        this.testSimpleDrawLegacy()
      }
    })
  },

  // 旧版本简单绘制测试
  testSimpleDrawLegacy() {
    console.log('旧版本简单绘制测试')
    
    const ctx = wx.createCanvasContext('overlayCanvas')
    
    // 清除画布
    ctx.clearRect(0, 0, 400, 400)
    
    // 绘制测试图形
    ctx.setFillStyle('red')
    ctx.fillRect(50, 50, 100, 100)
    
    ctx.setFillStyle('blue')
    ctx.fillRect(200, 50, 100, 100)
    
    ctx.setFillStyle('green')
    ctx.fillRect(50, 200, 100, 100)
    
    ctx.draw()
    
    console.log('旧版本简单绘制测试完成')
  },

  // 检查结果数据
  checkResultsData() {
    console.log('=== 检查结果数据 ===')
    const results = this.data.results
    console.log('结果数组:', results)
    console.log('结果数量:', results.length)
    
    if (results.length > 0) {
      results.forEach((item, index) => {
        console.log(`项目 ${index}:`, {
          question: item.question,
          userAnswer: item.userAnswer,
          correctAnswer: item.correctAnswer,
          isCorrect: item.isCorrect,
          confidence: item.confidence,
          type: item.type,
          position: item.position
        })
      })
    } else {
      console.log('没有结果数据')
    }
  },

  // 强制更新Canvas的CSS样式
  updateCanvasStyle(canvas, width, height) {
    console.log('强制更新Canvas样式:', width, height)
    
    // 通过DOM操作强制更新Canvas样式
    const query = wx.createSelectorQuery()
    query.select('#overlayCanvas').fields({ node: true, size: true }).exec((res) => {
      if (res[0] && res[0].node) {
        const canvasNode = res[0].node
        
        // 强制设置Canvas的CSS样式
        if (canvasNode.style) {
          canvasNode.style.width = width + 'px'
          canvasNode.style.height = height + 'px'
          canvasNode.style.position = 'absolute'
          canvasNode.style.top = '0px'
          canvasNode.style.left = '0px'
          canvasNode.style.zIndex = '10'
          
          console.log('Canvas样式已强制更新')
        }
      }
    })
  },

  // 模拟测试数据
  createTestData() {
    console.log('创建测试数据')
    const testResults = [
      {
        id: 1,
        question: '12 + 8 = ?',
        userAnswer: '19',
        correctAnswer: '20',
        isCorrect: false,
        confidence: 0.9,
        type: 'basic',
        position: { x: 50, y: 50, width: 150, height: 40 }
      },
      {
        id: 2,
        question: '25 ÷ 4 = ?',
        userAnswer: { quotient: 6, remainder: 1 },
        correctAnswer: { quotient: 6, remainder: 1 },
        isCorrect: true,
        confidence: 0.95,
        type: 'division_with_remainder',
        position: { x: 50, y: 100, width: 180, height: 40 }
      },
      {
        id: 3,
        question: '7 × 8 = ?',
        userAnswer: '54',
        correctAnswer: '56',
        isCorrect: false,
        confidence: 0.85,
        type: 'basic',
        position: { x: 50, y: 150, width: 150, height: 40 }
      },
      {
        id: 4,
        question: '15 - 9 = ?',
        userAnswer: '7',
        correctAnswer: '6',
        isCorrect: false,
        confidence: 0.75,
        type: 'basic',
        position: { x: 50, y: 200, width: 150, height: 40 }
      }
    ]

    this.setData({
      results: testResults
    })

    console.log('测试数据创建完成，开始绘制')
    this.drawOverlay()
  }
})
